<template>
  <div>
    <div class="mb-3">
      <el-button v-if="noFile" type="primary" @click="edit()">增加产业信息</el-button>

      <el-button v-if="noFile" type="primary" @click="dialogImportVisible = true">
        <i class="fa fa-fw fa-upload"></i>
        导入产业信息
      </el-button>
    </div>

    <loading-wrap>
      <el-table border :data="tableData">
        <el-table-column label="产品名称" prop="product_name"></el-table-column>
        <el-table-column align="center" label="主导产业" prop="is_main_product">
          <template slot-scope="scope">
            <span>
              <i
                v-if="scope.row.is_main_product === '1'"
                class="fa fa-check"
                style="color: #42bd56"
              ></i>
              <i v-else class="fa fa-close"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="基地类型" prop="base_type_name">
          <template slot-scope="scope">
            <span>{{ scope.row.base_type_name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品品类" prop="category_name">
          <template slot-scope="scope">
            <span>{{ scope.row.category_name || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="种养方式">
          <template slot-scope="scope">
            <span>{{ enumBreedType[scope.row.breed_type] || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="投产时间">
          <template slot-scope="scope">
            <span>{{ scope.row.input_date | timeDay }}</span>
          </template>
        </el-table-column>
        <el-table-column label="规模">
          <template slot-scope="scope">
            <span>{{ scope.row.scale | pureUnit(scope.row.uscale) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="库存" prop="store_num">
          <template slot-scope="scope">
            {{ scope.row.store_num || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="current_year_output" :label="`${year}年产量`">
          <template slot-scope="scope">
            {{ scope.row.current_year_output || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="last_year_output" :label="`${year - 1}年产量`">
          <template slot-scope="scope">
            {{ scope.row.last_year_output || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="llast_year_output" :label="`${year - 2}年产量`">
          <template slot-scope="scope">
            {{ scope.row.llast_year_output || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="品牌信息">
          <template slot-scope="scope">
            <div v-if="scope.row.brand_type && scope.row.brand_type.length">
              <span v-for="(p, index) of scope.row.brand_type" :key="index">
                {{ enumBrandType[p] || '-' }}
              </span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌竞争力" min-width="160">
          <template slot-scope="scope">
            <span>{{ enumBrandPowerType[scope.row.brand_power_type] || '-' }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column label="产业实景照片">-->
        <!--<template slot-scope="scope">-->
        <!--<img-card :images="scope.row.product_images"></img-card>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column v-if="noFile" label="操作">
          <template v-if="scope.row.submit_type !== '1'" slot-scope="scope">
            <el-button class="py-0 px-1" type="text" @click="edit(scope.row)">
              <i class="fa fa-edit"></i>
            </el-button>
            <el-button class="py-0 px-1 text-danger" type="text" @click="deleteData(scope.row)">
              <i class="fa fa-trash"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </loading-wrap>

    <form-component
      ref="fc"
      :auto-init="false"
      :form-data="formData"
      :before-save="resetMainProduct"
      :table-data="editData"
      :table-id="tableId"
      :table-name="tableName"
      :visible.sync="editVisible"
      @success="getData"
    ></form-component>

    <import-excel
      :visible.sync="dialogImportVisible"
      title="导入产业信息"
      :post-api="postUrl"
      excel-template="/static/files/产业信息导入模板.xlsx"
      @success="handleImportSucess"
    ></import-excel>
  </div>
</template>
<script>
import FormComponent from '@/components/FormComponent'
import SelectBaseType from '@/components/select/SelectBaseType'
import SelectProductCate from '@/credit/components/select/SelectProductCate'
import {
  enumBrandPowerType,
  enumBrandType,
  enumBreedType,
  enumMainType,
} from '@/credit/plugins/enum'
import ImportExcel from '@/components/ImportExcel'
const year = new Date().getFullYear()

export default {
  components: {
    FormComponent,
    ImportExcel,
  },
  props: {},
  data() {
    return {
      postUrl: '',
      dialogImportVisible: false,
      tableData: [],
      year,
      enumBreedType,
      enumBrandType,
      enumBrandPowerType,
      //
      isMainProduct: '0',
      //
      editVisible: false,
      tableName: 'datum_customer_industrial',
      formData: {
        product_name: { type: 'text', label: '产品名称', value: '', required: true },
        // is_main_product: {type: 'radio', label: '主导产业', value: '1', enumType: enumMainType, inline: true, required: true},
        is_main_product: {
          type: 'radio',
          label: '主导产业',
          value: '0',
          enumType: enumMainType,
          inline: true,
          required: true,
          onClick: v => {
            this.isMainProduct = v
          },
        },
        base_type: {
          type: 'component',
          label: '基地类型',
          value: '',
          component: SelectBaseType,
          attrs: { css: 'form-control-ml' },
          hide: true,
        },
        base_type_name: { type: 'text', label: '基地名称', value: '', hide: true },
        category_code: {
          type: 'component',
          label: '产品品类',
          value: '',
          required: true,
          component: SelectProductCate,
          attrs: {
            filterable: true,
            style: 'width: 360px',
          },
          on: {
            select: (a, b) => {
              const ref = this.$refs.fc
              const baseType = a ? a.substr(0, 4).padEnd(12, '0') : ''
              const baseLabel = b.length ? b[0] : ''
              const label = b.length > 1 ? b[b.length - 1] : baseLabel
              ref.setKey('base_type', 'value', baseType)
              ref.setKey('base_type_name', 'value', baseLabel)
              ref.setKey('category_name', 'value', label)
            },
          },
        },
        category_name: { type: 'text', label: '品类名称', value: '', hide: true },
        breed_type: {
          type: 'radio',
          label: '种养方式',
          value: '1',
          inline: true,
          enumType: enumBreedType,
        },
        scale: { type: 'number', label: '规模', value: '' },
        store_num: { type: 'number', value: '', label: '现有库存量' },
        uscale: { type: 'text', label: '单位', value: '' },
        input_date: { type: 'date', label: '投产时间', value: '' },
        llast_year_output: { type: 'number', label: `${year - 2}年产量`, value: '' },
        last_year_output: { type: 'number', label: `${year - 1}年产量`, value: '' },
        current_year_output: { type: 'number', label: `${year}年产量`, value: '' },
        output_unit: { type: 'text', label: '产量单位', value: '' },
        brand_type: {
          type: 'checkbox',
          label: '品牌信息',
          inline: true,
          value: [],
          enumType: enumBrandType,
          redundancy: fd => fd.brand_type.value.join(','),
        },
        brand_power_type: {
          type: 'radio',
          label: '品牌竞争力',
          value: '1',
          enumType: enumBrandPowerType,
        },
        // product_images: {type: 'image', label: '产业实景照片', value: ''}
      },
      tableId: '',
      editData: {},
      //
      customerData: {},
    }
  },
  computed: {
    noFile() {
      return this.customerData.project_status === '0' || this.customerData.project_status === '2'
    },
  },
  watch: {},
  created() {
    this.id = this.$route.query.id || sessionStorage.getItem('customer_related_id')

    this.postUrl =
      '/api/credit/import/?importKey=datum_customer_industrial_template&where=' +
      encodeURIComponent(
        '"datum_customer_industrial.service_id".eq(' + this.$store.getters.org.clientId + ')'
      ) +
      encodeURIComponent('&"datum_customer_industrial.customer_related_id".eq(' + this.id + ')')
    this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view'))

    this.getData()
  },
  mounted() {},
  methods: {
    async getData() {
      const [res] = await this.$utils.promise(
        this.$api.getData('credit', this.tableName, { 'customer_related_id.eq': this.id })
      )
      this.tableData = (res && res.data) || []
    },

    resetMainProduct() {
      if (this.isMainProduct === '1') {
        return new Promise((resolve, reject) => {
          this.$api
            .updateDataBody(
              'credit',
              'datum_customer_industrial',
              { 'customer_related_id.eq': this.id },
              { is_main_product: '0' }
            )
            .then(() => {
              resolve()
            })
            .catch(e => {
              reject(new Error(e))
            })
        })
      } else {
        return null
      }
    },

    edit(p) {
      this.editVisible = true
      this.tableId = p ? p.id : ''
      this.editData = p
      if (p && typeof p.brand_type === 'string') {
        this.editData.brand_type = this.editData.brand_type.split(',')
      }
    },
    // 导入
    handleImportSucess() {
      this.getData()
      this.dialogImportVisible = false
    },
    deleteData(item) {
      const h = this.$createElement
      this.$msgbox({
        title: '提示',
        message: h('span', undefined, `确定删除该产品？`),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            const [res] = await this.$utils.promise(
              this.$api.deleteData('credit', this.tableName, item.id)
            )
            instance.confirmButtonLoading = false
            instance.confirmButtonText = '确定'
            if (res) {
              this.$message.success('删除成功！')
              this.getData()
              done()
            } else {
              this.$message.error('删除失败，请重试！')
            }
          } else {
            done()
          }
        },
      }).catch(() => {})
    },
  },
}
</script>
<style scoped></style>
